package com.wisdytech.linkdcs.equipLifeCycle.check.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.wisdytech.common.utils.PojoConvertUtil;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.CheckModelItemBakDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckModelItemBak;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.ImportExcelUtils;
import com.wisdytech.linkdcs.account.model.TtEqEquipmentAid;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckDetailRecordDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckModelItemDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckModelItem;
import com.wisdytech.linkdcs.equipLifeCycle.check.service.ICheckModelItemService;
import com.wisdytech.linkdcs.equipLifeCycle.check.service.ICheckService;
import com.wisdytech.linkdcs.equipment.dao.IEqModelDao;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.ToolConfig;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dailibo
 * @since 2018-06-05
 */
@Service
@Transactional
public class CheckModelItemServiceImpl extends BaseService<ICheckModelItemDao, CheckModelItem> implements ICheckModelItemService {

	
	private Logger logger =LoggerFactory.getLogger(getClass());
	
	
    /**
     * 注入设备类别dao
     */
    @Resource
    private IEqModelDao modelDao;
	@Autowired
	private ICheckModelItemDao iCheckModelItemDao;
    @Autowired
    private CheckModelItemBakDao checkModelItemBakDao;
	
	@Autowired
	private ICheckService iCheckService;
	
	@Override
	public boolean add(CheckModelItem item,String createUser) {

        //判断点检编码是否唯一
        EntityWrapper<CheckModelItem> ew =new EntityWrapper<>();
        Integer count =iCheckModelItemDao.selectCount(
                ew.eq("CHECK_ITEM_CODE", item.getCheckItemCode())
                        .eq("DEL_FLAG", "0"));
        if(count>0) {
            throw new ServiceException("点检项目编码已存在");
        }
        String pkId = BaseUtil.getUUID();
        String snapshotId = BaseUtil.getUUID();
        item.setPkId(pkId);
        item.setDelFlag("0");
        item.setCreateUser(createUser);
        item.setCreateDate(new Date());
        item.setUpdateDate(new Date());
        item.setVersion(snapshotId);
        if(iCheckModelItemDao.insert(item)<=0) {
            throw new ServiceException("保存点检项目失败");
        }
        CheckModelItem snapshot = iCheckModelItemDao.selectById(pkId);
        CheckModelItemBak mItem = PojoConvertUtil.convertPojo(snapshot, CheckModelItemBak.class);
        mItem.setDelFlag(CommonConstants.DEL_FLAG);
        mItem.setPkId(snapshotId);
        if(checkModelItemBakDao.insert(mItem)<=0) {
            throw new ServiceException("保存快照失败");
        }
        // 保存点检项目后，点检管理中增加一条点检记录
        return iCheckService.addCheckRecordByModel(item.getModelCode(),createUser);
    }

	@Override
	public boolean update(CheckModelItem item,String udpateUser) {

        CheckModelItem oldItem =
                iCheckModelItemDao.selectById(item.getPkId());
        //编码改变，查看编码是否唯一
        if(!oldItem.getCheckItemCode().equals(item.getCheckItemCode())) {
            //判断点检编码是否唯一
            EntityWrapper<CheckModelItem> ew =new EntityWrapper<>();
            Integer count =iCheckModelItemDao.selectCount(
                    ew.eq("CHECK_ITEM_CODE", item.getCheckItemCode())
                            .eq("DEL_FLAG", CommonConstants.DEL_FLAG));
            if(count>0) {
                throw new ServiceException("点检项目编码已存在");
            }
        }

        //更新
        String snapshotId = BaseUtil.getUUID();
        item.setUpdateUser(udpateUser);
        item.setUpdateDate(new Date());
        item.setVersion(snapshotId);
        if(iCheckModelItemDao.updateById(item)<=0) {
            throw new ServiceException("更新点检项目失败");
        }
        CheckModelItem snapshot = iCheckModelItemDao.selectById(item.getPkId());
        CheckModelItemBak mItem = PojoConvertUtil.convertPojo(snapshot, CheckModelItemBak.class);
        mItem.setDelFlag(CommonConstants.DEL_FLAG);
        mItem.setPkId(snapshotId);
        if(checkModelItemBakDao.insert(mItem)<=0) {
            throw new ServiceException("保存快照失败");
        }
        return true;
    }

	@Override
	public boolean del(String itemIds,String createUser) {
		String[] itemIdList=
				itemIds.split(",");
		
		CheckModelItem  itemModel =
				iCheckModelItemDao.selectById(itemIdList[0]);
		
		for(String itemId : itemIdList) {
			CheckModelItem item =new CheckModelItem();
			item.setPkId(itemId);
			item.setUpdateUser(createUser);
			item.setUpdateDate(new Date());
			item.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
			if(!item.updateById()) {
				throw new ServiceException("删除点检项目失败");
			}
		}
		
		//判断设备型号下是否还有点检项目
		if(iCheckModelItemDao.selectCount(
				new EntityWrapper<CheckModelItem>()
					.eq("DEL_FLAG", CommonConstants.DEL_FLAG)
					.eq("MODEL_CODE", itemModel.getModelCode()))<=0) {
			//根据点检项目id判断是否修改点检管理
			return iCheckService.delCheckRecordByModel(itemModel.getModelCode(),createUser);
		}
		return true;
	}

	@Override
	public PageInfo<CheckModelItem> listCheckModelItems(Filter filter, String modelCode) {
		
		EntityWrapper<CheckModelItem> ew=new EntityWrapper<>();
		List<CheckModelItem>  lists =this.beforeList(ICheckModelItemDao.class, filter)
			.selectList(ew.eq("DEL_FLAG", CommonConstants.DEL_FLAG)
					.eq("MODEL_CODE", modelCode));
		
		return new PageInfo<CheckModelItem>(lists);
	}

	@Override
	public PageInfo<CheckModelItem> listCheckModelItemsByCheckId(Filter filter, String checkId) {
		
		
		List<CheckModelItem>  reuslt =this.beforeList(ICheckModelItemDao.class, filter)
			.selectDetailByCheckId(checkId);
		
		return new PageInfo<CheckModelItem>(reuslt);
	}

	@Override
	public CheckModelItem getItemById(String pkId) {
		// TODO Auto-generated method stub
		return iCheckModelItemDao.selectById(pkId);
	}

	@Override
	public void batchImportCheck(MultipartFile file, SysUser operator) {

        if (file == null) {
            throw new ServiceException("文件为空");
        }
        if (operator ==null) {
            throw new ServiceException("操作人不能为空");
        }
        int errorRow=0;
        try {
            String fileName = file.getOriginalFilename();
            InputStream in = file.getInputStream();
            List<List<Object>> data = ImportExcelUtils.getDataListByExcel(in, fileName);
            if (data == null || data.size() == 0) {
                throw new ServiceException("表格数据为空");
            }
            List<ToolConfig> list = new ArrayList<>();
            //i 从1开始，去除表头数据，根据自己的模板而定
            for (int i = 1; i < data.size(); i++) {
            	  errorRow = i;
            	  CheckModelItem item = new CheckModelItem();
            	  item.setPkId(BaseUtil.getUUID());
            	  item.setDelFlag(CommonConstants.DEL_FLAG);
            	  item.setCreateDate(new Date());
            	  item.setCreateUser(operator.getUsername());
                  if (data.get(i).get(0) == null||StringUtils.isBlank(data.get(i).get(0).toString())) {
                      throw new ServiceException("第"+i+"行第1列设备型号数据不能为空");
                  }
                  if(!checkModelCode(data.get(i).get(0).toString())) {
                      throw new ServiceException("第"+i+"行第1列设备型号数据在数据库中不存在");
                  }
                  item.setModelCode(data.get(i).get(0).toString());
                  if (data.get(i).get(1) == null||StringUtils.isBlank(data.get(i).get(1).toString())) {
                      throw new ServiceException("第"+i+"行第2列点检编号数据不能为空");
                  }
                  if(checkCheckItemCode(data.get(i).get(1).toString())) {
                      throw new ServiceException("第"+i+"行第2列点检项目编号已存在");
                  }
                  item.setCheckItemCode(data.get(i).get(1).toString());
                  item.setCheckItemName(data.get(i).get(2).toString());
                  item.setCheckMethod(data.get(i).get(3).toString());
                  item.setCheckStandard(data.get(i).get(4).toString());
                  item.setMaxValue(Double.parseDouble(data.get(i).get(5).toString()));
                  item.setStandardValue(Double.parseDouble(data.get(i).get(6).toString()));
                  item.setMinValue(Double.parseDouble(data.get(i).get(7).toString()));
                  item.setRemark(data.get(i).get(8).toString());
                  iCheckModelItemDao.insert(item);
                  // 保存点检项目后，点检管理中增加一条点检记录
          		  iCheckService.addCheckRecordByModel(item.getModelCode(),operator.getCreateUser());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件出错");
        } catch (IndexOutOfBoundsException e2) {
            e2.printStackTrace();
            throw new ServiceException("表格中第"+errorRow+"存在空数据");
        } 
		
	}
	
	private boolean checkCheckItemCode(String string) {
		//判断点检编码是否唯一
		EntityWrapper<CheckModelItem> ew =new EntityWrapper<>();
		Integer count =iCheckModelItemDao.selectCount(
				ew.eq("CHECK_ITEM_CODE", string)
				.eq("DEL_FLAG", "0"));
		return count>0;
	}

	private Boolean checkModelCode(String modelCode) {
        if (StringUtils.isBlank(modelCode)) {
            return false;
        }
        EntityWrapper<EquipModel> ew = new EntityWrapper<>();
        ew.eq("model_code",modelCode).eq("del_flag",CommonConstants.DEL_FLAG);
        return modelDao.selectCount(ew)>0;
    }

	

}
